package com.controller;

import com.webserver.annotations.Controller;
import com.webserver.annotations.RequestMapping;
import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;
import com.vo.User;
import org.apache.log4j.Logger;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 当前类用于完成与用户数据相关的业务处理
 */
@Controller
public class UserController {
    public static final Logger logger = Logger.getLogger(UserController.class);

    private static File USER_DIR = new File("./users");

    static {
        if (!USER_DIR.exists()) {//若该目录不存在!
            USER_DIR.mkdirs();//创建该目录
        }
    }

    @RequestMapping("/myweb/showAllUser")
    public void showAllUser(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("开始处理用户列表页面!!!!!!!!!!!!");
        //1从users目录中将所有的obj文件反序列化为User对象并存入一个集合备用。
        List<User> userList = new ArrayList<>();
        File[] subs = USER_DIR.listFiles(f -> f.getName().endsWith(".obj"));
        for (File file : subs) {
            try (
                    FileInputStream fis = new FileInputStream(file);
                    ObjectInputStream ois = new ObjectInputStream(fis);
            ) {
                User user = (User) ois.readObject();
                userList.add(user);
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        System.out.println(userList.size());
        //2生成页面，将所有用户数据包含进去
        PrintWriter pw = response.getWriter();
        pw.println("<!DOCTYPE html>");
        pw.println("<html lang=\"en\">");
        pw.println("<head>");
        pw.println("<meta charset=\"UTF-8\">");
        pw.println("<title>用户列表</title>");
        pw.println("</head>");
        pw.println("<body>");
        pw.println("<center>");
        pw.println("<h1>用户列表</h1>");
        pw.println("<table border=\"1\">");
        pw.println("<tr>");
        pw.println("<td>用户名</td>");
        pw.println("<td>密码</td>");
        pw.println("<td>昵称</td>");
        pw.println("<td>年龄</td>");
        pw.println("</tr>");
        for (User user : userList) {
            pw.println("<tr>");
            pw.println("<td>" + user.getUsername() + "</td>");
            pw.println("<td>" + user.getPassword() + "</td>");
            pw.println("<td>" + user.getNickname() + "</td>");
            pw.println("<td>" + user.getAge() + "</td>");
            pw.println("</tr>");
        }
        pw.println("</table>");
        pw.println("</center>");
        pw.println("</body>");
        pw.println("</html>");

        //设置响应头指定动态数据的类型
        response.setContentType("text/html");

        System.out.println("处理用户列表页面完毕!!!!!!!!!!!!");
    }

    @RequestMapping("/myweb/login")
    public String login(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("开始处理登录!!!!!!!!!!!!");
        //1获取页面提交上来的登录信息
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if (username == null || password == null) {
            return "/myweb/login_info_error.html";
        }
        //2
        File userFile = new File(USER_DIR, username + ".obj");
        if (userFile.exists()) {//文件存在才说明用户名输入正确
            try (
                    FileInputStream fis = new FileInputStream(userFile);
                    ObjectInputStream ois = new ObjectInputStream(fis);
            ) {
                User user = (User) ois.readObject();
                if (user.getPassword().equals(password)) {//若密码一致则登录成功
                    return "/myweb/login_success.html";
                }
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        System.out.println("处理登录完毕!!!!!!!!!!!!");
        return "/myweb/login_fail.html";

    }

    @RequestMapping("/myweb/reg")
    public String reg(HttpServletRequest request, HttpServletResponse response) {
        logger.info("开始处理注册！！！！！！！！！！！！！！");
        //1通过请求对象获取用户在reg.html页面中表单里输入的注册信息
        /*
            注意:getParameter()传入的参数要与页面上表单中该输入框的
            名字一致(输入框name属性指定的值)
         */
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String nickname = request.getParameter("nickname");
        String ageStr = request.getParameter("age");
        logger.info(username + "," + password + "," + nickname + "," + ageStr);
        /*
            对数据进行验证工作:
            要求用户名，密码，昵称，年龄都不能为null。并且年龄必须是一个数字(正则表达式验证)。
            如果不符合上述要求，直接向响应对象这中设置一个错误提示页:./webapps/myweb/reg_info_error.html
            该页面居中显示一行字:注册信息输入有误，请重新注册.
         */
        if (username == null || password == null || nickname == null || ageStr == null ||
                !ageStr.matches("[0-9]+")) {
            return "/myweb/reg_info_error.html";
        }

        int age = Integer.parseInt(ageStr);//将年龄的字符串转换为一个int值
        //2将该用户信息以一个User对象序列化到文件中保存
        User user = new User(username, password, nickname, age);
        /*
            File的构造方法:
            File(File parent,String child)
            表示子项child在parent目录下
         */
        File userFile = new File(USER_DIR, username + ".obj");

        /*
            检查是否为重复用户，若该用户已存在，则直接响应页面通知用户
            ./webapps/myweb/reg_have_user.html
            该页面居中显示一行字:该用户已存在，请重新注册
         */
        if (userFile.exists()) {
            return "/myweb/reg_have_user.html";
        }

        try (
                FileOutputStream fos = new FileOutputStream(userFile);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
        ) {
            oos.writeObject(user);
        } catch (IOException e) {
           logger.error(e.getMessage(),e);
        }
        //3设置响应对象回复给用户一个注册结果页面(成功或失败)
        logger.info("处理注册完毕！！！！！！！！！！！！！！");
        return "/myweb/reg_success.html";
    }
}
